
<template>
  <div class="content">
    <div class="subject-title">
      <span>主题名称：{{ subjectData.subjectName }}</span>
      <span>主题编码：{{ subjectData.subjectCode }}</span>
    </div>
    <el-row :gutter="10" class="mb8">
      <template v-if="type !== '0'">
        <el-col :span="1.5" >
          <el-button
            type="success"
            icon="el-icon-plus"
            size="mini"
            :disabled="!includedFormQueryParams.subjectCode"
            v-hasPermi="['items:subject:batchAddServiceSubject']"
            @click="handleAddSubjectForm"
          >增加主题关联表单
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="checkedFormCodes.length === 0"
            @click="handleDelete"
            v-hasPermi="['item:subject:removeServiceSubject']"
          >删除
          </el-button>
        </el-col>
      </template>

      <el-col :span="1.5" style="float: right">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getIncludedFormList"/>
        </el-tooltip>
      </el-col>

    </el-row>
    <el-table
      v-loading="listLoading"
      :data="includedFormList"
      @selection-change="includedFormListSelectionChange"

    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="表单名称" align="center" prop="formName"/>
      <el-table-column label="表单唯一标识" width="190" align="center" prop="formKey"/>
      <el-table-column label="最后更新时间" align="center" prop="updateTime"/>
      <el-table-column label="排序号" align="center" prop="sort" width="80px"/>
      <el-table-column label="是否可用" align="center" prop="formStatus" width="100px">
        <template slot-scope="scope">
          {{ scope.row.enable === 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" >
          <el-button
            v-if="type !== '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditSort(scope.row)"
            v-hasPermi="['item:subject:editServiceSubject']"
          >修改排序号
          </el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="lookFormExample(scope.row)"
          >查看样表
          </el-button> -->
          <el-button
            v-if="type !== '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['item:subject:removeServiceSubject']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="includedFormTotal>0"
      :total="includedFormTotal"
      :page.sync="includedFormQueryParams.pageNum"
      :limit="includedFormQueryParams.pageSize"
      layout="total, prev, pager, next, jumper"
      @pagination="getIncludedFormList"
    />

    <el-dialog
      :visible.sync="openAddFormDialog"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      @close="closeAddFormDialogCallback"
    >
      <template slot="title">增加主题关联表单 【{{ subjectData.subjectName }}】</template>
      <div style="margin-bottom: 20px">
        <el-input
          v-model="addFormSearchKeyword"
          placeholder="请输入表单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQueryCanAddForm"
          style="width: 300px; margin-right: 10px"
        />
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQueryCanAddForm">搜索</el-button>
      </div>
      <el-table
        max-height="500px"
        v-loading="includedFormDialogLoading"
        :data="canAddFormList"
        @selection-change="handleAddFormSelectionChange"
        ref="addAssociateFormTable"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="表单名称" align="center" prop="formName"/>
        <el-table-column label="表单唯一标识" align="center" prop="formKey"/>
        <el-table-column label="排序号" align="center" prop="sort" width="140px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.sort"
              size="small"
              :min="0"
              :precision="0"
              label="请输入排序号"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否可用" align="center" prop="formStatus" width="100px">
          <template slot-scope="scope">
            {{ scope.row.formStatus === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <!-- <template slot-scope="scope" >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="lookFormExample(scope.row)"
            >查看样表
            </el-button>
          </template> -->
        </el-table-column>
      </el-table>
      <pagination
        v-show="canAddFormTotal>0"
        :total="canAddFormTotal"
        :page.sync="addFormQueryParams.pageNum"
        :limit="addFormQueryParams.pageSize"
        layout="total, prev, pager, next, jumper"
        @pagination="handleAddFormPageChange"
      />
      <div slot="footer" class="dialog-footer">
        <div class="tip">
          注意：可选勾选多页多个表单一次性添加
        </div>
        <div class="right-wrap">
          <el-button type="primary" @click="handleSaveIncludedForms">确 定</el-button>
          <el-button @click="openAddFormDialog = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <edit-sort-dialog
      :value="currentEditSortRow.sort || 0"
      :dialog-visible="openEditFormSortDialog"
      @setDialogVisible="setDialogVisible"
      @sort-confirm="handleSortConfirm"
    />

    <form-example v-model="formExampleDialog"/>

  </div>
</template>

<script>
import {
  getListFormSubject,
  getListExcludeForm,
  batchAddFormSubject,
  removeFormSubject,
  editFormSubject
} from "@/api/items/subject";
import EditSortDialog from "@/views/items/subject/components/EditSortDialog";
import FormExample from "./formExample"
export default {
  name: "IncludeForms",
  components: {EditSortDialog, FormExample},
  props: {
    subjectData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      // 主题包含表单多选框已选中行
      checkedFormCodes: [],
      // 包含的表单列表
      includedFormList: [],
      // 包含表单加载中
      listLoading: false,
      includedFormTotal: 0,
      canAddFormTotal: 0,
      // 是否展示包含表单弹窗
      openAddFormDialog: false,
      includedFormDialogLoading: false,
      // 获取当前主题包含的表单参数
      includedFormQueryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectCode: undefined
      },
      // 获取可添加表单列表参数
      addFormQueryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectCode: undefined,
        formName: undefined,
      },
      // 增加可关联表单列表
      canAddFormList: [],
      // 增加关联表单弹窗搜索关键字
      addFormSearchKeyword: '',
      // 添加关联表单弹窗当前页选中表单
      currentPageSelectedList: [],
      // 缓存多个页所有已选中表单
      cacheAllPageSelectedForms: [],
      // 显示修改序号弹窗
      openEditFormSortDialog: false,
      // 当前修改序号行数据
      currentEditSortRow: {},
      type: '',
      formExampleDialog: false,
      ids:[]
    }
  },
  methods: {
    // 表单类型文本
    typeLabel(value) {
      const typeMap = {
        1: '第三方系统表单',
        2: 'iframe表单',
        3: '接口对接的表单'
      }
      return typeMap[value]
    },
    // 确定修改排序号
    handleSortConfirm(value) {
      console.log(value);
      const params = {
        subjectCode: this.includedFormQueryParams.subjectCode,
        sort: value,
        id: this.currentEditSortRow.id,
        formKey: this.currentEditSortRow.formKey
      };
      // 修改主题内表单排序号
      editFormSubject(params).then(response => {
        this.openEditFormSortDialog = false;
        // 重新获取列表
        this.getIncludedFormList();
        this.$modal.msgSuccess("修改序号成功！");
      });
    },
    // 排序弹窗组件关闭
    setDialogVisible(boolean) {
      this.openEditFormSortDialog = boolean;
    },
    // 修改序号
    handleEditSort(row) {
      // 记录当前修改序号行的数据
      this.currentEditSortRow = row;
      this.openEditFormSortDialog = true;
    },
    lookFormExample(row) {
      alert("查看样表")
    },
    // 主题包含表单多选框改变
    includedFormListSelectionChange(selection) {
      this.checkedFormCodes = selection.map(item => item.formKey);
      this.ids = selection.map(item => item.id)
    },
    // 添加主题关联表单弹窗页数改变
    handleAddFormPageChange() {
      // 缓存已选中表单信息
      this.saveSelectedItemToCacheList();
      // 重新获取数据
      this.getCanAddFormList();
    },
    // 将选中项推入缓存列表，未选中的从缓存列表删除
    saveSelectedItemToCacheList() {
      // 保存当前页所有ids
      const currentPageIds = this.canAddFormList.map(item => item.id);

      // 将当前页数据从缓存中删除，再将已选中的加入到缓存
      this.cacheAllPageSelectedForms = this.cacheAllPageSelectedForms.filter(item => {
        return !currentPageIds.includes(item.id)
      }).concat(this.currentPageSelectedList);

      // 清空当前页缓存
      this.currentPageSelectedList = [];
      console.log("重新计算缓存", this.cacheAllPageSelectedForms);
    },

    // 关闭关联表单弹窗回调
    closeAddFormDialogCallback() {
      // 关闭弹窗后清空选中缓存列表和选中列表
      this.cacheAllPageSelectedForms = [];
      this.currentPageSelectedList = [];
      this.canAddFormList = [];
    },

    // 关联表单弹窗多选框选择改变
    handleAddFormSelectionChange(selection) {
      // 当前页选中列表
      this.currentPageSelectedList = selection;
    },

    // 删除主题关联表单
    handleDelete(row) {
      const id = row.id || this.ids
      const serviceCodes = row.formKey ? [row.formKey] : this.checkedFormCodes;
      // console.log(serviceCodes);
      const params = serviceCodes.map(formKey => {
        return {
          formKey,
          subjectCode: this.includedFormQueryParams.subjectCode,
          relFlag:'2'
        }
      })
      this.$modal.confirm('是否确认删除选中的关联表单？').then(() => {
        return removeFormSubject(id)
      }).then(() => {
        this.getIncludedFormList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    // 保存关联表单
    handleSaveIncludedForms() {
      // 缓存已选中表单信息
      this.saveSelectedItemToCacheList();
      // 如果没有选择表单提示选择
      if (!this.cacheAllPageSelectedForms.length) return this.$modal.msgWarning("请选择添加表单！");
      // 当前主题编码
      const subjectCode = this.includedFormQueryParams.subjectCode;

      // 给每一个表单添加主题编码
      const params = this.cacheAllPageSelectedForms.map(item => {
        return {
          ...item,
          subjectCode
        }
      })
      const relParams = this.cacheAllPageSelectedForms.map(item =>{
        return{
          formKey:item.formKey,
          relFlag:'1',
          subjectCode
        }
      })
      // 新增主题表单
      batchAddFormSubject(params).then(response => {
        //关联表单
        // relForm(relParams)
        this.openAddFormDialog = false;
        // 重新获取列表
        this.getIncludedFormList();
        this.$modal.msgSuccess("添加成功！");
      });

    },

    // 增加关联表单搜索按钮
    handleQueryCanAddForm() {
      // 缓存已选中表单信息
      this.saveSelectedItemToCacheList();
      this.addFormQueryParams.formName = this.addFormSearchKeyword;
      this.addFormQueryParams.pageNum = 1;
      this.getCanAddFormList();
    },

    // 获取当前主题包含的表单
    getIncludedFormList() {
      this.listLoading = true;
      // 获取该主题包含的表单
      getListFormSubject(this.includedFormQueryParams).then(response => {
        this.listLoading = false;
        this.includedFormTotal = response.total;
        this.includedFormList = response.rows;
      });
    },

    // 获取可增加关联表单列表
    getCanAddFormList() {
      this.includedFormDialogLoading = true;
      console.log(this.addFormQueryParams)
      getListExcludeForm(this.addFormQueryParams).then(response => {
        this.includedFormDialogLoading = false;
        this.canAddFormTotal = response.data.total;
        this.canAddFormList = response.data.tRelFormSubjectList.map(item => {
          const cacheItem = this.cacheAllPageSelectedForms.find(cacheItem => item.id === cacheItem.id);
          if(cacheItem){ // 存在缓存列表 自动回填序号
            item.sort = cacheItem.sort;
          }else{
            item.sort = 0;
          }
          return item
        });

        // 设置表格多选框默认选中
        this.$nextTick(() => {
          for (let i = 0; i < this.canAddFormList.length; i++) {
            const row = this.canAddFormList[i];
            if (this.cacheAllPageSelectedForms.some(item => row.formKey === item.formKey)) {
              this.$refs.addAssociateFormTable.toggleRowSelection(row);
            }
          }
        })
      });
    },

    // 增加关联表单按钮
    handleAddSubjectForm() {
      this.openAddFormDialog = true;
      // 重置为第一页
      this.addFormQueryParams.pageNum = 1;
      this.getCanAddFormList();
    },

    // 设置表单关联
    hanAddFormRelFlag(FormData){
      const params = FormData.map(item =>{
        return{
          ...item,
          relFlag:'1'
        }
      })
      // relForm(params).then(res =>{
      //   console.log(res);
      // })
    }
  },
  watch: {
    subjectData: {
      immediate: true,
      handler(newValue) {
        // 存在id
        if (newValue.id) {
          console.log('asdasdassdaasd',newValue);
          this.addFormQueryParams.subjectCode = newValue.subjectCode;
          // this.addFormQueryParams.formName = newValue.subjectName;
          this.includedFormQueryParams.subjectCode = newValue.subjectCode;
          // 获取包含的表单
          this.getIncludedFormList();
        }
      }
    },
  },
  mounted() {
    const {type} = this.$route.query;
    // 编辑类型 0：查看 1：修改 2：新增
    this.type = type;
  },
}
</script>

<style lang="scss" scoped>
.content {
  box-sizing: border-box;
  width: 100%;
  height: 100%;

  .subject-title {
    word-break: break-word;
    margin-bottom: 10px;
    span{
      line-height: 30px;

      &:first-child{
        margin-right: 40px;
      }
    }
  }

}
.dialog-footer {
  position: relative;

  .tip {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 16px;
    line-height: 36px;
    color: red;
  }
}

</style>

